package org.vy.app.ajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;

public class AjaxServlet extends HttpServlet {

	private static final long serialVersionUID = -4042217744802381128L;
	private static Map<String, String> SERVICE_MAP = new HashMap<String, String>();
	
	@Override
	public void init(ServletConfig config){
		Enumeration initParams = config.getInitParameterNames();
		String svcId = null;
		while(initParams.hasMoreElements()){
			svcId = (String)initParams.nextElement();
			SERVICE_MAP.put(svcId, config.getInitParameter(svcId));
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// set headers before accessing the Writer
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		try {
			String svcId = request.getParameter("svc");
			
			AjaxResponse resp = new AjaxResponse();
			resp.setRequest(parseRequest(request.getParameter("request")));

			IService service = (IService)Class.forName(SERVICE_MAP.get(svcId)).newInstance();
			Object output = service.execute(resp.getRequest(), request);
			
			resp.setResponse(output);
			
			JSON obj = JSONSerializer.toJSON(resp);
			out.write(obj.toString());
			out.flush();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		out.close();
	}
	
	private Map<String, String> parseRequest(String req){
		Map<String, String> map = new HashMap<String, String>();
		if(req == null || "".equals(req.trim()))
			return map;

		String[] nvPairs = req.split("&");
		for(String nvPair : nvPairs) {
			String[] pair = nvPair.split("=");
			if(pair.length > 1)
				map.put(pair[0], pair[1]);
			else
				map.put(pair[0], "");
		}
		
		return map;
	}
}